$(document).ready(function () {


    var dataTable = $('#articleManagerTable').dataTable({
        language: AJAX_DATA_TABLE_OPTIONS,
        searching: false,
        paging: true,
        // aoColumnDefs: [{"bSortable": false, aTargets: [1]}],
        stripeClasses: ["odd", "even"],
        cache: false,
        serverSide: true,
        processing: true,
        lengthMenu: [10, 20, 30, 40, 60, 100],
        ajax: {
            url: '/admin/article/getArticleList',
            type: 'POST',
            data: function (d) {
                var order = d.order[0];
                var column = d.columns[order.column];
                var orderColumnName;
                var orderDir;
                if (column.orderable) {
                    orderColumnName = column.data;
                    orderDir = order.dir;
                }
                //去除其他参数
                for (var temp in d) {
                    if (temp.indexOf("columns") === 0 || temp.indexOf("order") === 0 || temp.indexOf("search") === 0) { //以columns开头的参数删除
                        delete d[temp];
                    }
                }
                var myRequestParams = {};
                myRequestParams.orderColumnName = orderColumnName;
                myRequestParams.orderDir = orderDir;
                $.extend(d, myRequestParams);

            },
            dataType: 'json',
            dataFilter: function (json) {
                json = JSON.parse(json);
                var returnData = {};
                if (json.status === 20000) {
                    returnData.draw = json.data.draw;
                    returnData.recordsTotal = json.data.recordsTotal;//返回数据全部记录
                    returnData.recordsFiltered = json.data.recordsTotal;//后台不实现过滤功能，每次查询均视作全部结果
                    returnData.data = json.data.data;//返回的数据列表
                } else {
                    console.log(json.message);
                    returnData.draw = 0;
                    returnData.recordsTotal = 0;
                    returnData.recordsFiltered = 0;
                    returnData.data = [];
                }
                return JSON.stringify(returnData);//这几个参数都是datatable需要的，必须要
            }
        },
        columns: [
            {"data": "id"},
            {
                "data": "modifyTime",
                "render": function (data, type, row, meta) {
                    return (new Date(data)).Format("yyyy-MM-dd hh:mm:ss");
                }
            },
            {"data": "title"},
            {"data": "browseCount"}
        ],
        columnDefs: [
            {targets: 2, orderable: false},
            {
                targets: 4, orderable: false, data: null, render: function (data, type, row) {
                    var status = "还未知";
                    var color = 'btn-secondary';

                    switch (data.status) {
                        case 0:
                            status = "已发布";
                            color = 'btn-success';
                            break;
                        case 1:
                            status = "编辑中";
                            color = 'btn-info';
                            break;
                        case 2:
                            status = "已删除";
                            color = 'btn-danger';
                            break;
                    }
                    var access = '未知';
                    var accessColor = 'btn-secondary';
                    switch (data.access) {
                        case 0:
                            access = '公开';
                            accessColor = 'btn-success';
                            break;
                        case 1:
                            access = '成员';
                            accessColor = 'btn-info';
                            break;
                        case 2:
                            access = '自己';
                            accessColor = 'btn-danger';
                            break;
                    }

                    var result = '';
                    result += '<button type="button" class="btn btn-sm ' + color + '" disabled>' + status + '</button>' +
                        '<button type="button"  class="btn-margin-left btn-margin-right btn btn-sm ' + accessColor + '" disabled>' + access + '</button>';

                    result += '|';

                    result +=
                        '<a role="button" class="btn-margin-left btn btn-sm btn-primary article-detail" href="javascript:void(0)" data-article-id="' + data.id + '">详情</a>' +
                        '<a role="button" class="btn-margin-left btn btn-sm btn-secondary" href="/admin/article/editArticle?articleId=' + data.id + '&type=' + data.contentType + '">编辑</a>' +
                        '<a role="button" class="btn-margin-left btn btn-sm btn-info" href="' + data.articleUrl + '" target="_blank">预览</a>' +
                        '<a role="button" class="btn-margin-left btn btn-sm btn-danger article-status" href="javascript:void(0)">状态</a>';
                    return result;
                }
            }
        ]

    });


    $('#articleManagerTable tbody').on('click', '.article-detail', function () {
        var closestRow = $(this).closest('tr');
        var data = dataTable.api().row(closestRow).data();
        $("#detailModalCenter").modal('show');
        loadArticleDetail(data.id, data.contentType);
    });


    $('#articleManagerTable tbody').on('click', '.article-status', function () {
        var closestRow = $(this).closest('tr');
        var data = dataTable.api().row(closestRow).data();
        $('#currentArticleId').val(data.id);

        $("#detailModalCenterStatus").modal('show');

        $("input[name='radioStatus']").eq(data.status).prop("checked", 'checked');
        $("input[name='radioAccess']").eq(data.access).prop("checked", 'checked');

        if (parseInt(data.status) !== 0) {
            $("input[name='radioAccess']").prop('disabled', true);
        } else {
            $("input[name='radioAccess']").removeAttr('disabled');
        }
    });


    $("input[name='radioStatus']").change(function () {
        var value = parseInt($(this).prop("value"));
        if (value !== 0) {
            $("input[name='radioAccess']").eq(2).prop("checked", 'checked');
            $("input[name='radioAccess']").prop('disabled', true);
        } else {
            $("input[name='radioAccess']").removeAttr('disabled');
        }
    });

    $('#updateStatusAccess').on('click', function () {
        var articleId = $('#currentArticleId').val();
        if (articleId === '') {
            return;
        }
        $.post({
            url: '/admin/article/updateArticleStatus',
            data: {
                articleId: articleId,
                status: $("input[name='radioStatus']:checked").val(),
                access: $("input[name='radioAccess']:checked").val()
            },
            success: function (result) {
                $('#updateResult').attr('display', 'block');
                if (result.status === 20000) {
                    $('#modalButton').attr('href', '/admin/article/articleManager');
                    $('#modalButton').removeAttr('data-dismiss');
                    showModal("修改成功");
                } else {
                    showModal(result.message);
                }
            }
        });

    });

    $('#tipModal').on('hidden.bs.modal', function (e) {
        $('#modalTitle').html("提示");
        $('#modalContent').html("");
        $('#modalButton').attr('href', '#');
        $('#modalButton').attr('data-dismiss', 'modal');
    });

    // $('#detailModalCenterStatus').on('hidden.bs.modal', function (e) {
    // $("input[name='radioAccess']").eq(0).attr("checked", 'checked');
    // $("input[name='radioStatus']").eq(0).attr("checked", 'checked');
    // });

    function showModal(content, title) {
        if (title != null) {
            $('#modalTitle').html(title);
        }
        $('#modalContent').html(content);
        $("#tipModal").modal('show');
    }


    function loadArticleDetail(articleId, contentType) {
        $.post({
            url: '/admin/article/getArticleDetailByArticleId',
            data: {
                articleId: articleId,
                type: contentType
            },
            success: function (result) {
                console.log(result);
                if (result.status === 20000) {
                    var data = result.data;
                    console.log(data);
                    $('#detailModalLongTitle').html(data.data.title);
                    $('#contentUrl').val(data.data.articleUrl);
                    $('#createTime').val(new Date(data.data.createTime).Format("yyyy-MM-dd hh:mm:ss"));
                    $('#modifyTime').val(new Date(data.data.modifyTime).Format("yyyy-MM-dd hh:mm:ss"));

                }
            }
        });
    }

});